# coding: utf-8

import tkinter
import time
import threading
import random

height = 800
width = 800


class Choujiang:
    # 初始化魔术方法
    def __init__(self):
        # 准备好界面
        self.root = tkinter.Tk()
        self.root.title('抽奖 点奖牌可以删除 点撤销可以恢复上次奖牌')
        self.root.minsize(height, width)

        #
        #
        # self.myFrame = tkinter.Frame(self.root, width=800)
        # self.mySecondaryFrame = tkinter.Frame(self.root, width=800)
        # self.myCanvas = tkinter.Canvas(self.myFrame, width=800)
        # self.myScrollbar = tkinter.Scrollbar(self.myFrame, orient='vertical', command=self.myCanvas.yview)
        #
        # self.myCanvas.config(yscrollcommand=self.myScrollbar.set)
        #
        # self.myFrame.pack(fill='both', expand=True)
        # self.myScrollbar.pack(side="right", fill='y')
        # self.myCanvas.pack(side='right', fill='both', expand=True)



        # 声明一个是否按下开始的变量
        self.btn_choiced = None
        self.remove_list = []
        self.isloop = False
        self.newloop = False
        # 调用设置界面的方法
        self.setwindow()


        # button_window = self.myCanvas.create_window(0, 0, anchor='nw', window=self.mySecondaryFrame)
        #
        # self.myCanvas.bind('<Configure>', self.onResize)
        self.root.mainloop()

    def onResize(self, event):
        """Prints the scrollbar's position on window resize."""
        print(str(self.myScrollbar.get()))

    # 界面布局方法
    def setwindow(self):
        # 开始停止按钮
        self.entry = tkinter.Button(self.root, width=10, height=2, text='')
        self.entry['bg'] = 'green'
        # self.entry.grid(row=0, column=1, stick=tkinter.E)
        self.entry.place(x=10, y=10, width=50, height=50)
        self.btn_start = tkinter.Button(self.root, text='开始/停止', command=self.newtask, bg='gold')
        self.btn_start.place(x=100, y=10, width=680, height=40)

        self.btn_restart = tkinter.Button(self.root, text='撤销', command=self.add_button, bg='gold')
        self.btn_restart.place(x=10, y=50, width=780, height=40)

        self.list = []

        try:
            with open('list.txt', 'r', encoding='utf8') as f:
                for line in f:
                    self.list.append(line)
        except:
            try:
                with open('list.txt', 'r', encoding='gbk') as f:
                    for line in f:
                        self.list.append(line)
            except:
                pass
        self.girlfrends = []

        for index, name in enumerate(self.list):
            btn = tkinter.Button(self.root, text=name, bg='white')
            btn.bind("<Button-1>", self.remove_button)
            btn.place(x=10 + 60 * (index % (width // 60)), y=100 + 60 * (index // (width // 60)), width=50,
                      height=50)

            # btn.pack(fill='y', expand=True)
            # self.myCanvas.configure(scrollregion=(0, 0, 0, 300 + 60 * (index // (width // 60))))
            self.girlfrends.append(btn)

        # 将所有选项组成列表

    def rounds(self):
        while self.newloop:
            # 延时操作
            time.sleep(0.0001)
            # 将所有的组件背景变为白色
            # for x in self.girlfrends:
            #     x['bg'] = 'white'
            if self.btn_choiced and self.btn_choiced.winfo_exists():
                self.btn_choiced['bg'] = 'white'
            # 将当前数值对应的组件变色
            self.btn_choiced = random.choice(self.girlfrends)
            self.btn_choiced['bg'] = 'red'
            self.entry['text'] = self.btn_choiced['text']

    # 建立一个新线程的函数
    def newtask(self):
        if self.isloop == False:
            self.isloop = True
            self.newloop = True
            # 建立线程
            if self.btn_choiced and self.btn_choiced.winfo_exists():
                self.remove_list.append({
                    'x': self.btn_choiced.winfo_x(),
                    'y': self.btn_choiced.winfo_y(),
                    'text': self.btn_choiced['text'],
                    'width': self.btn_choiced.winfo_width(),
                    'height': self.btn_choiced.winfo_height(),
                })
                self.btn_choiced.destroy()
                self.girlfrends.remove(self.btn_choiced)
                self.btn_choiced = None

            t = threading.Thread(target=self.rounds)
            # 开启线程运行
            t.start()
            # 设置循环开始标志
        elif self.isloop == True:
            self.isloop = False
            self.newloop = False

    def add_button(self):
        if self.remove_list:
            data = self.remove_list.pop()
            btn = tkinter.Button(self.root, text=data['text'], bg='white')
            btn.bind("<Button-1>", self.remove_button)
            btn.place(x=data['x'], y=data['y'], width=data['width'],
                      height=data['height'])
            self.girlfrends.append(btn)

    def remove_button(self, event):
        btn = event.widget
        self.remove_list.append({
            'x': btn.winfo_x(),
            'y': btn.winfo_y(),
            'text': btn['text'],
            'width': btn.winfo_width(),
            'height': btn.winfo_height(),
        })
        btn.destroy()
        self.girlfrends.remove(btn)
        # for name in dir(event):
        #     print(name, getattr(event, name))
        # data = self.remove_list.pop()
        # btn = tkinter.Button(self.root, text=data['text'], bg='white')
        #
        # btn.place(x=data['x'], y=data['y'], width=data['width'],
        #           height=data['height'])
        # self.girlfrends.append(btn)


c = Choujiang()
